package com.unlcn.ils.sales.web.util;


import com.unlcn.ils.sales.backend.bo.AreaBO;
import com.unlcn.ils.sales.backend.service.OrderAddrService;
import freemarker.core.Environment;
import freemarker.ext.beans.BeansWrapper;
import freemarker.ext.beans.BeansWrapperBuilder;
import freemarker.template.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.Map;


/**
 * 页面下拉框汇总
 *
 */
@Component

public class DictDirectiveModel implements TemplateDirectiveModel {

        @Autowired
        private OrderAddrService orderAddrService;

/*    private String getPid(Map<?,?> params)throws TemplateException{
        String classCode = getParam(params, "classCode");
        if(Strings.isNullOrEmpty(id)){
            throw new TemplateModelException("没有指定要展示class_code的cid属性");
        }
        return classCode;
    }*/

    @Override
    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)throws TemplateException, IOException {
        String curCode = getParam(params, "curCode");

        //起运地
        String departRegionCode = getParam(params, "departRegionCode");

        //目的省 根据起运地id查询
        String destRegionProvince = getParam(params, "destRegionProvince");

        //目的市
        String destRegionCode = getParam(params, "destRegionCode");

        String startAreaId = null;

        try {
            if (StringUtils.isNotBlank(departRegionCode)){
                List<AreaBO> list= null ;
                list = orderAddrService.listAreaByCondition("");
                env.setVariable("items", createBeansWrapper().wrap(list));
                env.setVariable("currCode", createBeansWrapper().wrap(curCode));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        body.render(env.getOut());

    }

    protected String getParam(Map<?,?> params, String name) {

        Object value = params.get(name);

        if (value instanceof SimpleScalar) {

            return ((SimpleScalar)value).getAsString();

        }

        return null;

    }

    public BeansWrapper createBeansWrapper() {

        return new BeansWrapperBuilder(Configuration.VERSION_2_3_23).build();

    }
}
